//
//  SureGongXuViewController.m
//  MyProject
//
//  Created by Pei on 16/7/28.
//  Copyright © 2016年 Xiaobo Pei. All rights reserved.
//

#import "SureGongXuViewController.h"
#import "IHRefreshTableView.h"
#import "CheckAndAcceptCell.h"
#import "MultiSelectTableViewCell.h"
#import "GongXuDetailViewController.h"
#import "QualityScanViewController.h"
#import "UserInfo.h"
#import "SureGongXuDetailViewController.h"

@interface SureGongXuViewController ()<UITableViewDelegate, UITableViewDataSource,SureGongXuDetailViewControllerDelegate>
{
    IHRefreshTableView *_myTable;
    UIView *_headerView;
    
    UIButton *_rightBtn;
    
    UIControl *_addControl;
    UIView *_addView;
    
    NSString *_currentAction;
    NSArray *_dataArray;
    
    int pushType;
}

@end

@implementation SureGongXuViewController

- (id)initFromPush{
    self = [super init];
    if (self) {
        pushType = 1;
    }
    return self;
}

- (void)pushNavigationBack{
    [kAPPDelegate rootView];
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    [[NSNotificationCenter defaultCenter] postNotificationName:Hide_TabBar_Notification object:nil];
}


- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    if (pushType == 1) {
        UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 22, 22)];
        [backButton setBackgroundImage:[UIImage imageNamed:@"01back"] forState:UIControlStateNormal];
        [backButton setBackgroundImage:[UIImage imageNamed:@"01back"] forState:UIControlStateHighlighted];
        [backButton addTarget:self action:@selector(pushNavigationBack) forControlEvents:UIControlEventTouchUpInside];
        [self.navigationItem setLeftBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:backButton]];
        self.navigationItem.hidesBackButton = YES;
    }

    
    _rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 22)];
    [_rightBtn setTitle:@"编辑" forState:UIControlStateNormal];
    [_rightBtn setTitleColor:kBlueColor forState:UIControlStateNormal];
    _rightBtn.titleLabel.font = kAppFont(Home_Big_Size);
    [_rightBtn addTarget:self action:@selector(rightBtnAcion) forControlEvents:UIControlEventTouchUpInside];
    //[self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:_rightBtn]];
    
    
    _selFlags = [[NSMutableArray alloc] initWithCapacity:3];
    
    
    
    
    [self initTableView];
    //[self initTableHeaderView];
    
    _addControl = [[UIControl alloc] init];
    _addControl.frame = CGRectMake(0.0f, kDeviceHeight-NAV_HEIGHT-kTabHeight, kDeviceWidth, kTabHeight);
    [_addControl addTarget:self action:@selector(addControlAction) forControlEvents:UIControlEventTouchUpInside];
    _addControl.backgroundColor = kBtnBackgroundColor;
    [self.view addSubview:_addControl];
    
    //02edit@3x
    UILabel *btnTitle = [[UILabel alloc] initWithFrame:CGRectMake((kDeviceWidth-66)/2.0f, (_addControl.height-Home_Big_Size)/2.0f, 66, Home_Big_Size)];
    btnTitle.textColor = kWhiteColor;
    btnTitle.text = @"实体采集";
    btnTitle.font = kAppFont(Home_Big_Size);
    [_addControl addSubview:btnTitle];
    
    _addView = [[UIView alloc] init];
    _addView.hidden = YES;
    _addView.frame = CGRectMake(0.0f, kDeviceHeight-NAV_HEIGHT-kTabHeight, kDeviceWidth, kTabHeight);
    [self.view addSubview:_addView];
    
    //114 122 162
    UIButton *cancleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancleBtn.frame = CGRectMake(0.0f, 0.0f, kDeviceWidth/2.0f, kTabHeight);
    [cancleBtn setBackgroundColor:kRGB(114, 122, 162)];
    [cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancleBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    cancleBtn.titleLabel.font = kAppFont(Home_Big_Size);
    cancleBtn.tag = 116;
    [cancleBtn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    [_addView addSubview:cancleBtn];
    
    UIButton *uploadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    uploadBtn.frame = CGRectMake(kDeviceWidth/2.0f, 0.0f, kDeviceWidth/2.0f, kTabHeight);
    [uploadBtn setBackgroundColor:kBtnBackgroundColor];
    [uploadBtn setTitle:@"确认" forState:UIControlStateNormal];
    [uploadBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    uploadBtn.titleLabel.font = kAppFont(Home_Big_Size);
    [uploadBtn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    uploadBtn.tag = 118;
    [_addView addSubview:uploadBtn];
    
    
    //UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    //deleteBtn.frame = CGRectMake(kDeviceWidth/3.0f*2.0f, 0.0f, kDeviceWidth/3.0f, kTabHeight);
    //[deleteBtn setBackgroundColor:kRedColor];
    //[deleteBtn setTitle:@"删除" forState:UIControlStateNormal];
    //[deleteBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    //deleteBtn.titleLabel.font = kAppFont(Home_Big_Size);
    //deleteBtn.tag = 119;
    //[deleteBtn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    //[_addView addSubview:deleteBtn];
    
    [self getData];
}

- (void)getData{
    //Get_Sure_GuanJianGongXu
    [[YMNetLib getInstance] connectWithAction:Get_Sure_GuanJianGongXu method:@"GET" withContent:[NSString stringWithFormat:@"UserID=%@&PageIndex=%@&PageSize=%@",[[UserInfo getInstance] getUserID], @"1", @"10"] withBody:nil withDelegate:self];
    _currentAction = Get_Sure_GuanJianGongXu;
}

- (void)NetDoOverSuccess:(NSDictionary*)body
{
    if ([_currentAction isEqualToString:Get_Sure_GuanJianGongXu]){
        if ([[YMNetDataUtil getSuccessState:body] intValue] == 1){
            _dataArray = [body objectForKey:@"Items"];
            if (_dataArray !=nil && _dataArray.count > 0) {
                [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:_rightBtn]];
            }
            [_selFlags removeAllObjects];
            for (int i = 0; i < _dataArray.count; i++)
            {
                [_selFlags addObject:[NSNumber numberWithBool:NO]];
            }
            [_myTable reloadData];
        }
    }
}

- (void)rightBtnAcion
{
    [_myTable setEditing:!_myTable.editing animated:YES];
    
    _addControl.hidden = YES;
    _addView.hidden = NO;
    
    [self.navigationItem setRightBarButtonItem:nil];
}

- (void)addControlAction
{
    QualityScanViewController *qualityScanVC =  [[QualityScanViewController alloc] init];
    qualityScanVC.navTitle = @"实体采集";
    [self.navigationController pushViewController:qualityScanVC animated:YES];
}

- (void)btnAction:(UIButton*)sender
{
    switch (sender.tag) {
        case 116:
        {
            [_myTable setEditing:!_myTable.editing animated:YES];
            
            _addView.hidden = YES;
            _addControl.hidden = NO;
            
            [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:_rightBtn]];
        }
            break;
        case 118:
        {
            for (int i = 0; i < _dataArray.count; i++)
            {
                NSDictionary *tempD = [_dataArray objectAtIndex:i];
                if ([[tempD valueForKey:@"isSelect"] boolValue]) {
                    
                    [[YMUIUtil getInstance] hideLoadingView];
                    [[YMUIUtil getInstance] showLoadingWithTitle:@"加载中..."];
                    //[self loadingView];

                    
                    //Upload_Task
                    NSDictionary *bodyDic = [NSDictionary dictionaryWithObjectsAndKeys:
                                             [[UserInfo getInstance] getUserID],@"UserID",//UserID
                                             [NSNumber numberWithInt:[[tempD valueForKey:@"ID"] intValue]],@"ProcessId",
                                             @"",@"Remark",
                                             nil];
                    
                    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
                    //[manager.requestSerializer setValue:[[UserInfo getInstance] getUseToken] forHTTPHeaderField:@"UserToken"];
                    //[manager.requestSerializer setValue:[[UserInfo getInstance] getUserID] forHTTPHeaderField:@"UserUid"];
                    
                    manager.requestSerializer = [AFJSONRequestSerializer serializer];
                    manager.responseSerializer = [AFJSONResponseSerializer serializer];
                    [manager.requestSerializer setValue:[[UserInfo getInstance] getUseToken] forHTTPHeaderField:@"UserToken"];
                    [manager.requestSerializer setValue:[[UserInfo getInstance] getUserID] forHTTPHeaderField:@"UserUid"];
                    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
                    [manager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
                    
                    
                    NSString *urlStr = [NSString stringWithFormat:@"%@",kAppApi(Sure_GuanJianGongXu)];
                    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                    NSLog(@"url =  %@", urlStr);
                    NSMutableDictionary *tempDic = [[NSMutableDictionary alloc] initWithDictionary:bodyDic];
                    NSLog(@"bodybodybody====%@", [tempDic description]);
                    
                    [manager POST:urlStr parameters:tempDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                        NSDictionary *jsonDict = [YMUtil changeType:(NSDictionary*)responseObject];
                        NSLog(@"获取到的数据为：%@",jsonDict);
                        if ([[YMNetDataUtil getSuccessState:jsonDict] intValue] == 1){
                            [self getData];
                        }
                        NSLog(@"========error%@",[jsonDict valueForKey:@"Error"]);
                        [[YMUIUtil getInstance] hideLoadingView];
                        
                    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                        NSLog(@"发生错误！%@",error);
                        [[YMUIUtil getInstance] hideLoadingView];
                    }];
                    
                    
                }
            }
            
            [_myTable setEditing:!_myTable.editing animated:YES];
            
            _addView.hidden = YES;
            _addControl.hidden = NO;
            
            [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:_rightBtn]];

        }
            break;
        default:
            break;
    }
}

- (void)initTableView
{
    CGRect frame = CGRectMake(0, 0.0f, kDeviceWidth, kDeviceHeight-NAV_HEIGHT-kTabHeight);
    _myTable = [[IHRefreshTableView alloc] initWithFrame:frame refreshType:-1 andAutoLoad:NO];
    _myTable.delegate = self;
    _myTable.dataSource = self;
    _myTable.footer.hidden = YES;
    _myTable.header.hidden = YES;
    _myTable.allowsSelectionDuringEditing = YES;
    [self.view addSubview:_myTable];
}

- (void)initTableHeaderView
{
    _headerView = [[UIView alloc] init];
    _headerView.frame = CGRectMake(0.0f, 0.0f, kDeviceWidth, 40.0f);
    _headerView.backgroundColor = kWhiteColor;
    _myTable.tableHeaderView = _headerView;
    
    UIView *lineView0 = [[UIView alloc] init];
    lineView0.frame = CGRectMake(0.0f, 40.0f-0.5f, kDeviceWidth, 0.5f);
    lineView0.backgroundColor = kGreenColor;
    [_headerView addSubview:lineView0];
    
    
    UIView *lineView1 = [[UIView alloc] init];
    lineView1.frame = CGRectMake(kDeviceWidth/3.0f, 0.0f, 0.5f, 40.0f-0.5f);
    lineView1.backgroundColor = kGreenColor;
    [_headerView addSubview:lineView1];
    
    
    UIView *lineView2 = [[UIView alloc] init];
    lineView2.frame = CGRectMake(kDeviceWidth/3.0f*2.0f, 0.0f, 0.5f, 40.0f-0.5f);
    lineView2.backgroundColor = kGreenColor;
    [_headerView addSubview:lineView2];
    
    UIControl *lbl0Control = [[UIControl alloc] initWithFrame:CGRectMake(0.0f, 0.0f, kDeviceWidth/3.0f, 40.0f)];
    lbl0Control.tag = 116;
    [lbl0Control addTarget:self action:@selector(controlAction:) forControlEvents:UIControlEventTouchUpInside];
    [_headerView addSubview:lbl0Control];
    
    UIControl *lbl1Control = [[UIControl alloc] initWithFrame:CGRectMake(kDeviceWidth/3.0f, 0.0f, kDeviceWidth/3.0f, 40.0f)];
    lbl1Control.tag = 118;
    [lbl1Control addTarget:self action:@selector(controlAction:) forControlEvents:UIControlEventTouchUpInside];
    [_headerView addSubview:lbl1Control];
    
    UIControl *lbl2Control = [[UIControl alloc] initWithFrame:CGRectMake(kDeviceWidth/3.0f*2.0f, 0.0f, kDeviceWidth/3.0f, 40.0f)];
    lbl2Control.tag = 119;
    [lbl2Control addTarget:self action:@selector(controlAction:) forControlEvents:UIControlEventTouchUpInside];
    [_headerView addSubview:lbl2Control];
    
    //ic_down@2x.png
    UILabel *lbl0 = [[UILabel alloc] init];
    lbl0.frame = CGRectMake(0.0, (40-(Home_Small_Size+2.0f))/2.0f, kDeviceWidth/3.0f-26/2-2.0f, Home_Small_Size+2.0f);
    lbl0.font = kAppFont(Home_Small_Size+2.0f);
    lbl0.textColor = kBlackColor;
    lbl0.text = @"二公司";
    lbl0.textAlignment = NSTextAlignmentCenter;
    [lbl0Control addSubview:lbl0];
    
    UIImageView *arrowImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ic_down"]];
    arrowImageView.frame = CGRectMake(kDeviceWidth/3.0f-26.0f/2.0f-2.0f, (40-11.0f/2.0f)/2.0f, 26/2, 11.0f/2.0f);
    [lbl0Control addSubview:arrowImageView];
    
    UILabel *lbl1 = [[UILabel alloc] init];
    lbl1.frame = CGRectMake(0.0f, (40-(Home_Small_Size+2.0f))/2.0f, kDeviceWidth/3.0f-26/2-2.0f, Home_Small_Size+2.0f);
    lbl1.font = kAppFont(Home_Small_Size+2.0f);
    lbl1.textColor = kBlackColor;
    lbl1.text = @"全部项目";
    lbl1.textAlignment = NSTextAlignmentCenter;
    [lbl1Control addSubview:lbl1];
    
    UIImageView *arrowImageView1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ic_down"]];
    arrowImageView1.frame = CGRectMake(kDeviceWidth/3.0f-26.0f/2.0f-2.0f, (40-11.0f/2.0f)/2.0f, 26/2, 11.0f/2.0f);
    [lbl1Control addSubview:arrowImageView1];
    
    
    UILabel *lbl2 = [[UILabel alloc] init];
    lbl2.frame = CGRectMake(0.0f, (40-(Home_Small_Size+2.0f))/2.0f, kDeviceWidth/3.0f-26/2-2.0f, Home_Small_Size+2.0f);
    lbl2.font = kAppFont(Home_Small_Size+2.0f);
    lbl2.textColor = kBlackColor;
    lbl2.text = @"全部工序";
    lbl2.textAlignment = NSTextAlignmentCenter;
    [lbl2Control addSubview:lbl2];
    
    UIImageView *arrowImageView2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ic_down"]];
    arrowImageView2.frame = CGRectMake(kDeviceWidth/3.0f-26.0f/2.0f-2.0f, (40-11.0f/2.0f)/2.0f, 26/2, 11.0f/2.0f);
    [lbl2Control addSubview:arrowImageView2];
}

//- (void)controlAction:(UIControl*)sender
//{
//    switch (sender.tag) {
//        case 116:
//        {
//            SelectCompanyAndProjectViewController *selectVC = [[SelectCompanyAndProjectViewController alloc] init];
//            [self.navigationController pushViewController:selectVC animated:YES];
//        }
//            break;
//        case 118:
//        {
//            SelectCompanyAndProjectViewController *selectVC = [[SelectCompanyAndProjectViewController alloc] init];
//            [self.navigationController pushViewController:selectVC animated:YES];
//        }
//            break;
//        case 119:
//        {
//            ShiGongStatusViewController *shiGongVC = [[ShiGongStatusViewController alloc] init];
//            shiGongVC.delegate = self;
//            [self.navigationController pushViewController:shiGongVC animated:YES];
//        }
//            break;
//
//        default:
//            break;
//    }
//}


- (void)passSelectStatus:(NSDictionary *)tempDic{
    
}


#pragma mark  ************************* UITableViewDataSource **************************************
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return (nil == _selFlags) ? 0 : _selFlags.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"MultiSelectTableViewCell";
    CheckAndAcceptCell *cell = (CheckAndAcceptCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil)
    {
        cell = [[CheckAndAcceptCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSDictionary *ddd = [_dataArray objectAtIndex:indexPath.row];
    [cell showWithData:ddd];
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    //[_selFlags moveObjectFromIndex:sourceIndexPath.row toIndex:destinationIndexPath.row];
}


#pragma mark -
#pragma mark Table view delegate

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleNone;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.isEditing)
    {
        MultiSelectTableViewCell *cell = (MultiSelectTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
        [cell changeMSelectedState];
        //[_selFlags replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:cell.mSelected]];
        
        NSDictionary *tempDic = [_dataArray objectAtIndex:indexPath.row];
        NSMutableArray *tempArray = [[NSMutableArray alloc] initWithArray:_dataArray];
        for (int i = 0; i < tempArray.count; i++)
        {
            NSMutableDictionary *tempD = [[NSMutableDictionary alloc] initWithDictionary:[tempArray objectAtIndex:i]];
            if ([[tempDic valueForKey:@"ID"] intValue] == [[tempD valueForKey:@"ID"] intValue]) {
                //[NSNumber numberWithBool:YES], @"isSelect"
                //[tempD setValue:@"1" forKey:@"isSelect"];
                //[tempD removeObjectForKey:@"isSelect"];
                [tempD setObject:[NSNumber numberWithBool:cell.mSelected] forKey:@"isSelect"];
                [tempArray replaceObjectAtIndex:i withObject:tempD];
            }
        }
        
        _dataArray = tempArray;
    }
    else
    {
        NSDictionary *ddd = [_dataArray objectAtIndex:indexPath.row];
        SureGongXuDetailViewController *GXVC = [[SureGongXuDetailViewController alloc] initWithData:ddd];
        GXVC.navTitle = @"详情";
        GXVC.delegate = self;
        [self.navigationController pushViewController:GXVC animated:YES];
    }
}

- (void)passRloadData{
    [self getData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
